package com.longxi.tianjintianbao.ui.presenter.main;

import android.content.Intent;
import android.view.View;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.greedao.controller.DataUserController;
import com.longxi.tianjintianbao.greedao.entity.User;
import com.longxi.tianjintianbao.ui.activity.login.LoginActivity;
import com.longxi.tianjintianbao.ui.activity.main.MainActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.main.ISplashAtView;
import com.longxi.tianjintianbao.utils.MyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SplashAtPresenter extends BasePresenter<ISplashAtView> {

    private Long recLen = Long.valueOf(3);
    Timer timer = null;

    public SplashAtPresenter(BaseActivity context) {
        super(context);
    }

    public void getAppInitInfo(){
        autoLogon();
    }

    String username = "";
    String password = "";

    public void autoLogon(){
        if(MyApplication.loginUser != null){
//            MyApplication.IP = getSp("IP");
//            MyApplication.IPID = getSp("IPID");
//            MyApplication.COMPANY = getSp("COMPANY");

            if("".equals(MyApplication.IPID)){
                return;
            }
            username = MyApplication.loginUser.getLoginUsername();
            password = MyApplication.loginUser.getLoginPassword();
            login();
        }else{
            timer = new Timer();
            timer.schedule(task, 1000, 1000);
            if(getView().getBtnJump() != null){
                getView().getBtnJump().setVisibility(View.VISIBLE);
                getView().getBtnJump().setText("跳转"+recLen);
            }
        }
    }

    /**
     * 登录
     * username 用户名
     * password 密码
     */
    public void login() {
        JSONObject object = new JSONObject();
        try {
            object.put("username", username);
            object.put("password", password);
            object.put("identification", AppConst.identification);
//            object.put("identification", "1104a89792fa498b4fe");
            object.put("phonetype", "ANDROID");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ApiRetrofit.getInstance().login(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<User>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                MyUtils.showToast(throwable.message);
                //到登录页
                mContext.jumpToActivityAndClearTask(LoginActivity.class);
            }

            @Override
            public void onNext(HttpResult<User> user) {
                mContext.hideWaitingDialog();
                if(user.getCode() != 0){
                    MyUtils.showToast(user.getMsg());
                    //到登录页
                    mContext.jumpToActivityAndClearTask(LoginActivity.class);
                    return;
                }
                insertOrUpdate(user.getData().get(0), Long.parseLong(MyApplication.IPID), username, password);
            }
        });
    }

    /**
     * 更新或插入用户用户
     * @param user
     */
    public void insertOrUpdate(User user, long iptype, String username, String password){
        //讲选择的ip存储到用户喜好中
        saveSp("IP", MyApplication.IP);
        saveSp("IPID", MyApplication.IPID);
        saveSp("COMPANY", MyApplication.COMPANY);

        DataUserController.updateAllByIsLogin();
        user.setIsLogin("1");//是否通过该账号登录
        user.setIptype(iptype);
        user.setLoginUsername(username);//登录账号
        user.setLoginPassword(password);//登录密码
        user.setUpdateTime(new Date());
        User userOld = DataUserController.findUserByIptypeAndUserid(user);
        if(userOld != null){
            user.setId(userOld.getId());
            DataUserController.updateUser(user);
        }else{
            DataUserController.insertUser(user);
        }
        goHome(user);
    }

    public void goHome(User user){
        JPushInterface.getRegistrationID(MyApplication.getInstance());
        MyApplication.loginUser = user;
        mContext.hideWaitingDialog();
        MyUtils.showToast("登录成功");
        Intent intent = new Intent(mContext, MainActivity.class);
        if("".equals(user.buildid) || user.buildid == null){
            intent = new Intent(mContext, LoginActivity.class);
            mContext.startActivity(intent);
            mContext.finish();
        }else{
            mContext.startActivity(intent);
            mContext.finish();
        }
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            mContext.runOnUiThread(new Runnable() {      // UI thread
                @Override
                public void run() {
                    recLen--;
                    if(getView().getBtnJump() != null){
                        getView().getBtnJump().setText("跳转"+recLen);
                    }
                    if(recLen < 1){
                        mContext.jumpToActivityAndClearTask(LoginActivity.class);
                    }
                }
            });
        }
    };

    public void getHome(){
        timerCancel();
        mContext.jumpToActivityAndClearTask(LoginActivity.class);
    }

    public void timerCancel(){
        if(timer != null){
            timer.cancel();
        }

    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != mContext.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case AppConst.IntentRequstCode.ACTIVITY_SELECT_COMMUNITY:
                mContext.jumpToActivity(MainActivity.class);
                mContext.finish();
                break;
        }
    }

    @Override
    public void detachView() {
        super.detachView();
        this.task = null;
        this.timer = null;
    }
}
